# username = json_dict.get('username')
# password = json_dict.get('password')
# mobile = json_dict.get('mobile')
# sms_code = json_dict.get('sms_code')
# allow = json_dict.get('allow')

from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from .models import User
import re

class LoginSerializer(ModelSerializer):
    """
    注册
    """
    sms_code = serializers.CharField(min_length=6)
    allow = serializers.BooleanField(allow_null=False)
    password2 = serializers.CharField(min_length=8, max_length=20)
    class Meta:
        model = User
        fields = ["username", "password", "mobile", "sms_code", "allow", "password2"]
        extra_kwargs = {
            'password': {'write_only': True, 'min_length': 8, 'max_length': 20}, # password只参与反序列化
            'username': {'min_length': 3, 'max_length': 20},
        }
        
    def create(self, validated_data):
        validated_data.pop("sms_code")
        validated_data.pop("allow")
        validated_data.pop("password2")
        # 新建用户需要加密密码
        instance = User.objects.create_user(**validated_data)
        return instance
    

    def validate(self, attrs):
        if attrs["password"] != attrs["password2"]:
            raise serializers.ValidationError("两次密码不一致")
        if not re.match(r'^1[3-9]\d{9}$', attrs['mobile']):
            raise serializers.ValidationError("密码格式有误")
        return attrs

    
     